﻿using OCR.Config;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace OCR.SystemThread
{
    internal class CameraTriggerThread_Modbus
    {
        public static bool CameraTrigger_Flowrec = false;
        public static Thread CameraTriggerFlow_Thread = null;
        public static int iCameraTrigger_Step = 0;

        public static bool CameraTrigger_Stop = false;
        public static void CameraTrigger_Thread()
        {
            CameraTrigger_Flowrec = true;
            CameraTriggerFlow_Thread = new Thread(CameraTriggerFlowThread);
            CameraTriggerFlow_Thread.IsBackground = true;
            CameraTriggerFlow_Thread.Start();
            Console.WriteLine("iCameraTrigger_Step: " + iCameraTrigger_Step);
        }

        private static void CameraTriggerFlowThread(object obj)
        {
            while (CameraTrigger_Flowrec)
            {
                switch (iCameraTrigger_Step)
                {
                    case 0:
                        //AlgorithmModule.ImageHandleV2_Refresh(Application.StartupPath + "\\TemplateInput\\Refresh.bmp");

                        break;
                    case 5:
                        AlgorithmModule.ImageHandleV2_Refresh(Application.StartupPath + "\\TemplateInput\\Refresh.bmp");
                        if (CameraReceiveThread.isImageData)
                        {

                            DateTime imgDateTime = DateTime.Now;
                            Console.WriteLine("  modbus抓图时长：" + (imgDateTime - CameraReceiveThread.imageDateTime).TotalMilliseconds);
                           
                            Console.WriteLine("frameForSave.Image0:  " + CameraReceiveThread.frameForSave.Image);

                            //AlgorithmModule.ImageHandleV2_Modbus_Zoom();
                            //AlgorithmModule.ImageHandleV2();

                            DateTime dt1 = DateTime.Now;

                            Rectangle cropRect = new Rectangle
(int.Parse(LocalTemplateInfo.rect_X) * 2,
int.Parse(LocalTemplateInfo.rect_Y) * 2,
(int.Parse(LocalTemplateInfo.rect_Right) - int.Parse(LocalTemplateInfo.rect_X)) * 2,
(int.Parse(LocalTemplateInfo.rect_Bottom) - int.Parse(LocalTemplateInfo.rect_Y)) * 2);
                            // OCR_Form.oCR_Form.mainCameraPb.Image = AlgorithmModule.CropImage(CameraReceiveThread.frameForSave.Image.ToBitmap(), cropRect, "cropTest.bmp");
                            //Image tempImg = AlgorithmModule.CropImageNoRect_opencv(CameraReceiveThread.frameForSave.Image.ToBitmap(), cropRect);
                            Image tempImg = AlgorithmModule.CropImageNoRect_opencv_nousing(CameraReceiveThread.frameForSave.Image.ToBitmap(), cropRect, "", "", LocalInfo.imgScale);
                            if (tempImg == null)
                            {
                                Console.WriteLine("裁剪区域无效");
                            }
                            LocalInfo.totalCount += 1;
                            DateTime dt2 = DateTime.Now;
                            Bitmap finalBit = (Bitmap)CameraReceiveThread.frameForSave.Image.ToBitmap().Clone();
                            //if (OCR_Form.oCR_Form.mainCameraPb.InvokeRequired)
                            //{
                            //    OCR_Form.oCR_Form.mainCameraPb.BeginInvoke(new Action(() => OCR_Form.oCR_Form.mainCameraPb.Image = AlgorithmModule.RectPoints(finalBit, AlgorithmModule.convertList)));
                            //}
                            //else
                            //{
                            //    OCR_Form.oCR_Form.mainCameraPb.Image = AlgorithmModule.RectPoints(finalBit, AlgorithmModule.convertList);
                            //}

                            CameraReceiveThread.isImageData = false;
                            CameraReceiveThread.frameForSave = null;
                            DateTime dt2_Rect = DateTime.Now;

                            if (OCR_Form.oCR_Form.InfoTB_01_Modbus.InvokeRequired)
                            {
                                OCR_Form.oCR_Form.InfoTB_01_Modbus.BeginInvoke(new Action(() => OCR_Form.oCR_Form.InfoTB_01_Modbus.Text = string.Empty));
                            }
                            else
                            {
                                OCR_Form.oCR_Form.InfoTB_01_Modbus.Text = string.Empty;
                            }

                            if (OCR_Form.oCR_Form.InfoTB_02_Modbus.InvokeRequired)
                            {
                                OCR_Form.oCR_Form.InfoTB_02_Modbus.BeginInvoke(new Action(() => OCR_Form.oCR_Form.InfoTB_02_Modbus.Text = string.Empty));
                            }
                            else
                            {
                                OCR_Form.oCR_Form.InfoTB_02_Modbus.Text = string.Empty;
                            }

                            if (OCR_Form.oCR_Form.InfoTB_03_Modbus.InvokeRequired)
                            {
                                OCR_Form.oCR_Form.InfoTB_03_Modbus.BeginInvoke(new Action(() => OCR_Form.oCR_Form.InfoTB_03_Modbus.Text = string.Empty));
                            }
                            else
                            {
                                OCR_Form.oCR_Form.InfoTB_03_Modbus.Text = string.Empty;
                            }

                            if (OCR_Form.oCR_Form.InfoTB_04_Modbus.InvokeRequired)
                            {
                                OCR_Form.oCR_Form.InfoTB_04_Modbus.BeginInvoke(new Action(() => OCR_Form.oCR_Form.InfoTB_04_Modbus.Text = string.Empty));
                            }
                            else
                            {
                                OCR_Form.oCR_Form.InfoTB_04_Modbus.Text = string.Empty;
                            }

                            if (OCR_Form.oCR_Form.InfoTB_05_Modbus.InvokeRequired)
                            {
                                OCR_Form.oCR_Form.InfoTB_05_Modbus.BeginInvoke(new Action(() => OCR_Form.oCR_Form.InfoTB_05_Modbus.Text = string.Empty));
                            }
                            else
                            {
                                OCR_Form.oCR_Form.InfoTB_05_Modbus.Text = string.Empty;
                            }

                            if (OCR_Form.oCR_Form.InfoTB_06_Modbus.InvokeRequired)
                            {
                                OCR_Form.oCR_Form.InfoTB_06_Modbus.BeginInvoke(new Action(() => OCR_Form.oCR_Form.InfoTB_06_Modbus.Text = string.Empty));
                            }
                            else
                            {
                                OCR_Form.oCR_Form.InfoTB_06_Modbus.Text = string.Empty;
                            }

                            if (AlgorithmModule.currConfigs.Count >= 1)
                            {
                                if (OCR_Form.oCR_Form.InfoTB_01_Modbus.InvokeRequired)
                                {
                                    OCR_Form.oCR_Form.InfoTB_01_Modbus.BeginInvoke(new Action(() => OCR_Form.oCR_Form.InfoTB_01_Modbus.Text = AlgorithmModule.currConfigs[0].text));
                                }
                                else
                                {
                                    OCR_Form.oCR_Form.InfoTB_01_Modbus.Text = AlgorithmModule.currConfigs[0].text; ;
                                }
                            }
                            if (AlgorithmModule.currConfigs.Count >= 2)
                            {
                                if (OCR_Form.oCR_Form.InfoTB_02_Modbus.InvokeRequired)
                                {
                                    OCR_Form.oCR_Form.InfoTB_02_Modbus.BeginInvoke(new Action(() => OCR_Form.oCR_Form.InfoTB_02_Modbus.Text = AlgorithmModule.currConfigs[1].text));
                                }
                                else
                                {
                                    OCR_Form.oCR_Form.InfoTB_02_Modbus.Text = AlgorithmModule.currConfigs[1].text; ;
                                }
                            }
                            if (AlgorithmModule.currConfigs.Count >= 3)
                            {
                                if (OCR_Form.oCR_Form.InfoTB_03_Modbus.InvokeRequired)
                                {
                                    OCR_Form.oCR_Form.InfoTB_03_Modbus.BeginInvoke(new Action(() => OCR_Form.oCR_Form.InfoTB_03_Modbus.Text = AlgorithmModule.currConfigs[2].text));
                                }
                                else
                                {
                                    OCR_Form.oCR_Form.InfoTB_03_Modbus.Text = AlgorithmModule.currConfigs[2].text; ;
                                }
                            }
                            if (AlgorithmModule.currConfigs.Count >= 4)
                            {
                                if (OCR_Form.oCR_Form.InfoTB_04_Modbus.InvokeRequired)
                                {
                                    OCR_Form.oCR_Form.InfoTB_04_Modbus.BeginInvoke(new Action(() => OCR_Form.oCR_Form.InfoTB_04_Modbus.Text = AlgorithmModule.currConfigs[3].text));
                                }
                                else
                                {
                                    OCR_Form.oCR_Form.InfoTB_04_Modbus.Text = AlgorithmModule.currConfigs[3].text; ;
                                }
                            }
                            if (AlgorithmModule.currConfigs.Count >= 5)
                            {
                                if (OCR_Form.oCR_Form.InfoTB_05_Modbus.InvokeRequired)
                                {
                                    OCR_Form.oCR_Form.InfoTB_05_Modbus.BeginInvoke(new Action(() => OCR_Form.oCR_Form.InfoTB_05_Modbus.Text = AlgorithmModule.currConfigs[4].text));
                                }
                                else
                                {
                                    OCR_Form.oCR_Form.InfoTB_05_Modbus.Text = AlgorithmModule.currConfigs[4].text; ;
                                }
                            }
                            if (AlgorithmModule.currConfigs.Count >= 6)
                            {
                                if (OCR_Form.oCR_Form.InfoTB_06_Modbus.InvokeRequired)
                                {
                                    OCR_Form.oCR_Form.InfoTB_06_Modbus.BeginInvoke(new Action(() => OCR_Form.oCR_Form.InfoTB_06_Modbus.Text = AlgorithmModule.currConfigs[5].text));
                                }
                                else
                                {
                                    OCR_Form.oCR_Form.InfoTB_06_Modbus.Text = AlgorithmModule.currConfigs[5].text; ;
                                }
                            }
                            DateTime dt2_Rect_Info = DateTime.Now;
                            if (!File.Exists("ImageResult.txt"))
                            {
                                File.WriteAllText("ImageResult.txt", null, Encoding.UTF8);
                            }
                            DateTime dt2_Rect_Info_ResultFile = DateTime.Now;
                            //try
                            //{
                            //    StreamWriter sw = File.AppendText("ImageResult.txt");
                            //    sw.WriteLine(DateTime.Now.ToString("opencv-记录时间：" + "yyyy:MM:dd:HH:mm:ss.fffffff") + "  " + "进算法：" + dt1.TimeOfDay + "  " + "出算法：" + dt2.TimeOfDay + "  " + "算法间隔：" + (dt2 - dt1).TotalMilliseconds);//yyyy:MM:dd:HH:mm:ss.fffff
                            //    sw.Close();
                            //}
                            //catch (Exception e)
                            //{

                            //    Console.WriteLine(e.Message);
                            //}
                            bool isSame = LocalTemplateInfo.CompareTemplate(AlgorithmModule.currConfigs);
                            DateTime dt2_Rect_Info_ResultFile_Compare = DateTime.Now;
                            //Console.WriteLine(isSame);
                            if (!isSame)
                            {
                                Console.WriteLine("opencv-NG");

                                OCR_Form.ModbusSendNg();
                                LocalInfo.ngCount +=1;
                                DateTime SendNgDt = DateTime.Now;

                                OCR_Form.oCR_Form.mainCameraPb.Image = AlgorithmModule.RectPoints(finalBit, AlgorithmModule.convertList);
                                OCR_Form.oCR_Form.tbNGResult1.Text = "NG";
                                try
                                {
                                    StreamWriter sw = File.AppendText("ImageResult.txt");
                                    string timeResult_ng = DateTime.Now.ToString("NG_opencv_记录时间：" + "yyyy:MM:dd:HH:mm:ss.fffffff")
                                        + "  算法时长：" + (dt2 - dt1).TotalMilliseconds
                                        + "  克隆相机图片时长：" + (dt2_Rect - dt2).TotalMilliseconds
                                        + "  主界面设置信息时长：" + (dt2_Rect_Info - dt2_Rect).TotalMilliseconds
                                        + "  无日志创建日志时长：" + (dt2_Rect_Info_ResultFile - dt2_Rect_Info).TotalMilliseconds
                                        + "  模板比较时长：" + (dt2_Rect_Info_ResultFile_Compare - dt2_Rect_Info_ResultFile).TotalMilliseconds
                                        + "  发送NG时长：" + (SendNgDt - dt2_Rect_Info_ResultFile_Compare).TotalMilliseconds
                                        + "  modbus抓到图时间：" + imgDateTime.ToString("yyyy:MM:dd:HH:mm:ss:ffff")
                                        + "  总时长：" + (SendNgDt - dt1).TotalMilliseconds;
                                    Console.WriteLine(timeResult_ng);
                                    sw.WriteLine(timeResult_ng);
                                    sw.Close();
                                }
                                catch (Exception e)
                                {

                                    Console.WriteLine(e.Message);
                                }


                                //NG存图
                                Console.WriteLine("opencv-NG存图");
                                try
                                {
                                    string outImgPath = Application.StartupPath + "\\out\\";
                                    string tempPath = outImgPath + DateTime.Now.ToString("yyyy-MM-dd") + "\\";
                                    //Console.WriteLine(Directory.Exists(tempPath));
                                    if (!Directory.Exists(tempPath))
                                    {
                                        Directory.CreateDirectory(tempPath);
                                    }
                                    Console.WriteLine(tempPath);
                                    //CameraReceiveThread.frameForSave.Image.ToBitmap().Save(tempPath + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + "_NG" + ".bmp");
                                    //AlgorithmModule.RectPoints(CameraReceiveThread.frameForSave.Image.ToBitmap()).Save(tempPath + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + "_NG_A" + ".bmp");

                                    finalBit.Save(tempPath + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + "_NG" + ".bmp");
                                    AlgorithmModule.RectPoints(finalBit, AlgorithmModule.convertList).Save(tempPath + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + "_NG_A" + ".bmp");
                                }
                                catch (Exception e)
                                {
                                    Console.WriteLine(e.Message);
                                }
                            }
                            else
                            {
                                DateTime SendOKDt = DateTime.Now;
                                try
                                {
                                    StreamWriter sw = File.AppendText("ImageResult.txt");
                                    // sw.WriteLine(DateTime.Now.ToString("Ok_opencv_记录时间：" + "yyyy:MM:dd:HH:mm:ss.fffffff") + "  " + "进图：" + dt1.TimeOfDay + "  " + "发送OK：" + SendOKDt.TimeOfDay + "  " + "间隔：" + (SendOKDt - dt1).TotalMilliseconds);//yyyy:MM:dd:HH:mm:ss.fffff
                                    string timeResult_ok = DateTime.Now.ToString("Ok_opencv_记录时间：" + "yyyy:MM:dd:HH:mm:ss.fffffff")
    + "  算法时长：" + (dt2 - dt1).TotalMilliseconds
    + "  主界面画框时长：" + (dt2_Rect - dt2).TotalMilliseconds
    + "  主界面设置信息时长：" + (dt2_Rect_Info - dt2_Rect).TotalMilliseconds
    + "  无日志创建日志时长：" + (dt2_Rect_Info_ResultFile - dt2_Rect_Info).TotalMilliseconds
    + "  模板比较时长：" + (dt2_Rect_Info_ResultFile_Compare - dt2_Rect_Info_ResultFile).TotalMilliseconds
    + "  发送Ok时长：" + (SendOKDt - dt2_Rect_Info_ResultFile_Compare).TotalMilliseconds
    + "  总时长：" + (SendOKDt - dt1).TotalMilliseconds;
                                    Console.WriteLine(timeResult_ok);
                                    sw.WriteLine(timeResult_ok);
                                    sw.Close();
                                }
                                catch (Exception e)
                                {

                                    Console.WriteLine(e.Message);
                                }


                                string outImgPath = Application.StartupPath + "\\out\\";
                                string tempPath = outImgPath + DateTime.Now.ToString("yyyy-MM-dd") + "\\";
                                Console.WriteLine(Directory.Exists(tempPath));
                                if (!Directory.Exists(tempPath))
                                {
                                    Directory.CreateDirectory(tempPath);
                                }
                                Console.WriteLine("opencv-OK");
                                OCR_Form.oCR_Form.tbNGResult1.Text = "OK";
                                OCR_Form.oCR_Form.mainCameraPb.Image = AlgorithmModule.RectPoints(finalBit, AlgorithmModule.convertList);
                                if (OCR_Form.oCR_Form.saveImgCb_PLC.Checked || OCR_Form.oCR_Form.saveOKImgcB.Checked)
                                {
                                    //OK存图
                                    Console.WriteLine("opencv-ok存图");
                                    try
                                    {
                                        //CameraReceiveThread.frameForSave.Image.ToBitmap().Save(tempPath + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + "_OK" + ".bmp");
                                        //AlgorithmModule.RectPoints(CameraReceiveThread.frameForSave.Image.ToBitmap()).Save(tempPath + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + "_OK_A" + ".bmp");

                                        finalBit.Save(tempPath + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + "_OK" + ".bmp");
                                        AlgorithmModule.RectPoints(finalBit, AlgorithmModule.convertList).Save(tempPath + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + "_OK_A" + ".bmp");

                                    }
                                    catch (Exception e)
                                    {
                                        Console.WriteLine(e.Message);
                                    }
                                }
                            }




                        }
                        break;
                }
                Thread.Sleep(1);
            }
        }
    }
}
